package com.jiangnan.warehouse_management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiangnan.warehouse_management.common.exception.BusinessException;
import com.jiangnan.warehouse_management.dto.request.ItemRequest;
import com.jiangnan.warehouse_management.dto.request.ItemUpdateRequest;
import com.jiangnan.warehouse_management.dto.response.ItemDetailResponse;
import com.jiangnan.warehouse_management.dto.response.ItemQueryResponse;
import com.jiangnan.warehouse_management.dto.response.ItemResponse;
import com.jiangnan.warehouse_management.mapper.CategoryMapper;
import com.jiangnan.warehouse_management.mapper.ItemMapper;
import com.jiangnan.warehouse_management.pojo.Category;
import com.jiangnan.warehouse_management.pojo.Item;
import com.jiangnan.warehouse_management.service.ItemService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ItemServiceImpl implements ItemService {

    private final ItemMapper itemMapper;
    private final CategoryMapper categoryMapper;

    @Override
    public ItemQueryResponse getItems(Integer page, Integer pageSize, String itemName, Integer categoryId) {
        // 参数校验
        page = (page == null || page < 1) ? 1 : page;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;

        // 构建查询条件
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(itemName)) {
            queryWrapper.like(Item::getItemName, itemName);
        }
        if (categoryId != null) {
            queryWrapper.eq(Item::getCategoryId, categoryId);
        }
        queryWrapper.orderByDesc(Item::getCreatedAt);

        // 开启分页，必须在执行查询前调用
        PageHelper.startPage(page, pageSize, true);
        
        // 执行查询
        List<Item> items = itemMapper.selectList(queryWrapper);
        
        // 获取分页信息
        PageInfo<Item> pageInfo = new PageInfo<>(items);

        // 转换为响应对象
        List<ItemResponse> itemResponses = items.stream()
                .map(this::convertToItemResponse)
                .collect(Collectors.toList());

        // 构建返回结果
        ItemQueryResponse response = new ItemQueryResponse();
        response.setList(itemResponses);
        response.setTotal(pageInfo.getTotal());
        response.setPage(page);
        response.setPageSize(pageSize);

        return response;
    }

    @Override
    @Transactional
    public Item createItem(ItemRequest request) {
        // 检查分类是否存在
        Category category = categoryMapper.selectById(request.getCategoryId());
        if (category == null) {
            throw new BusinessException(404, "分类不存在");
        }

        // 检查物品名称是否已存在
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Item::getItemName, request.getItemName());
        Long count = itemMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(400, "物品名称已存在");
        }

        // 检查库存范围是否合理
        if (request.getMinimumStock() >= request.getMaximumStock()) {
            throw new BusinessException(400, "最小库存必须小于最大库存");
        }

        // 创建物品
        Item item = new Item();
        BeanUtils.copyProperties(request, item);
        
        // 插入数据
        int rows = itemMapper.insert(item);
        if (rows != 1) {
            throw new BusinessException(500, "创建物品失败");
        }

        return item;
    }

    @Override
    public ItemDetailResponse getItemById(Integer id) {
        // 参数校验
        if (id == null) {
            throw new BusinessException(400, "物品ID不能为空");
        }

        // 查询物品
        Item item = itemMapper.selectById(id);
        if (item == null) {
            throw new BusinessException(404, "物品不存在");
        }

        // 转换为响应对象
        ItemDetailResponse response = new ItemDetailResponse();
        BeanUtils.copyProperties(item, response);

        // 查询并设置分类信息
        if (item.getCategoryId() != null) {
            Category category = categoryMapper.selectById(item.getCategoryId());
            if (category != null) {
                ItemDetailResponse.CategoryDTO categoryDTO = new ItemDetailResponse.CategoryDTO();
                categoryDTO.setCategoryId(category.getCategoryId());
                categoryDTO.setCategoryName(category.getCategoryName());
                response.setCategory(categoryDTO);
            }
        }

        return response;
    }

    @Override
    @Transactional
    public ItemDetailResponse updateItem(Integer id, ItemUpdateRequest request) {
        // 参数校验
        if (id == null) {
            throw new BusinessException(400, "物品ID不能为空");
        }

        // 查询物品是否存在
        Item item = itemMapper.selectById(id);
        if (item == null) {
            throw new BusinessException(404, "物品不存在");
        }

        // 检查物品名称是否重复（排除当前物品）
        if (!item.getItemName().equals(request.getItemName())) {
            LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Item::getItemName, request.getItemName())
                    .ne(Item::getItemId, id);
            Long count = itemMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(400, "物品名称已存在");
            }
        }

        // 检查库存范围是否合理
        if (request.getMinimumStock() >= item.getMaximumStock()) {
            throw new BusinessException(400, "最小库存必须小于最大库存");
        }

        // 更新物品信息
        Item updateItem = new Item();
        updateItem.setItemId(id);
        updateItem.setItemName(request.getItemName());
        updateItem.setSpecification(request.getSpecification());
        updateItem.setMinimumStock(request.getMinimumStock());

        // 执行更新
        int rows = itemMapper.updateById(updateItem);
        if (rows != 1) {
            throw new BusinessException(500, "更新物品失败");
        }

        // 返回更新后的完整信息
        return getItemById(id);
    }

    @Override
    @Transactional
    public void deleteItem(Integer id) {
        // 参数校验
        if (id == null) {
            throw new BusinessException(400, "物品ID不能为空");
        }

        // 查询物品是否存在
        Item item = itemMapper.selectById(id);
        if (item == null) {
            throw new BusinessException(404, "物品不存在");
        }

        // TODO: 这里可以添加其他业务检查，比如检查物品是否被使用等
        // 例如：检查物品是否有关联的库存记录
        // 如果有关联数据，可以抛出异常提示用户先处理关联数据

        // 执行删除
        int rows = itemMapper.deleteById(id);
        if (rows != 1) {
            throw new BusinessException(500, "删除物品失败");
        }
    }

    private ItemResponse convertToItemResponse(Item item) {
        ItemResponse response = new ItemResponse();
        BeanUtils.copyProperties(item, response);

        // 查询并设置分类信息
        if (item.getCategoryId() != null) {
            Category category = categoryMapper.selectById(item.getCategoryId());
            if (category != null) {
                ItemResponse.CategoryDTO categoryDTO = new ItemResponse.CategoryDTO();
                categoryDTO.setCategoryId(category.getCategoryId());
                categoryDTO.setCategoryName(category.getCategoryName());
                response.setCategory(categoryDTO);
            }
        }

        return response;
    }
}
